{% extends 'dashboard/base.html' %}
{% load static %}

{% block title %}兑换记录管理 - 后台管理{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">兑换记录管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <a href="{% url 'dashboard:rewards_management' %}" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> 返回奖品管理
        </a>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <h6 class="card-title">总兑换数</h6>
                <h3>{{ total_exchanges }}</h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body">
                <h6 class="card-title">待处理</h6>
                <h3>{{ pending_exchanges }}</h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body">
                <h6 class="card-title">已完成</h6>
                <h3>{{ completed_exchanges }}</h3>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body">
                <h6 class="card-title">总消耗积分</h6>
                <h3>{{ total_points_used }}</h3>
            </div>
        </div>
    </div>
</div>

<!-- 搜索和筛选 -->
<div class="card shadow mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <input type="text" name="search" class="form-control" placeholder="搜索用户名、奖品名称..." value="{{ search_query }}">
            </div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">所有状态</option>
                    <option value="pending" {% if status_filter == 'pending' %}selected{% endif %}>待处理</option>
                    <option value="completed" {% if status_filter == 'completed' %}selected{% endif %}>已完成</option>
                    <option value="cancelled" {% if status_filter == 'cancelled' %}selected{% endif %}>已取消</option>
                </select>
            </div>
            <div class="col-md-2">
                <input type="date" name="date_from" class="form-control" placeholder="开始日期" value="{{ date_from }}">
            </div>
            <div class="col-md-2">
                <input type="date" name="date_to" class="form-control" placeholder="结束日期" value="{{ date_to }}">
            </div>
            <div class="col-md-1">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="bi bi-search"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 兑换记录列表 -->
<div class="card shadow">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>用户</th>
                        <th>奖品</th>
                        <th>消耗积分</th>
                        <th>状态</th>
                        <th>兑换时间</th>
                        <th>完成时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for exchange in exchanges %}
                    <tr id="exchange-{{ exchange.id }}">
                        <td>
                            <div class="d-flex align-items-center">
                                <img src="{{ exchange.user.get_avatar_url }}" alt="{{ exchange.user.username }}" 
                                     class="rounded-circle me-2" width="32" height="32">
                                <div>
                                    <strong>{{ exchange.user.nickname|default:exchange.user.username }}</strong>
                                    <br>
                                    <small class="text-muted">@{{ exchange.user.username }}</small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <div class="d-flex align-items-center">
                                {% if exchange.reward.image %}
                                <img src="{{ exchange.reward.image.url }}" alt="{{ exchange.reward.name }}" 
                                     class="rounded me-2" width="40" height="40" style="object-fit: cover;">
                                {% else %}
                                <div class="rounded bg-light d-flex align-items-center justify-content-center me-2" 
                                     style="width: 40px; height: 40px;">
                                    <i class="bi bi-gift text-muted"></i>
                                </div>
                                {% endif %}
                                <div>
                                    <strong>{{ exchange.reward.name }}</strong>
                                    <br>
                                    <small class="text-muted">{{ exchange.reward.get_type_display }}</small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge bg-danger">-{{ exchange.points_used }}</span>
                        </td>
                        <td>
                            {% if exchange.status == 'pending' %}
                                <span class="badge bg-warning">待处理</span>
                            {% elif exchange.status == 'completed' %}
                                <span class="badge bg-success">已完成</span>
                            {% else %}
                                <span class="badge bg-secondary">已取消</span>
                            {% endif %}
                        </td>
                        <td>{{ exchange.created_at|date:"Y-m-d H:i" }}</td>
                        <td>
                            {% if exchange.completed_at %}
                                {{ exchange.completed_at|date:"Y-m-d H:i" }}
                            {% else %}
                                <span class="text-muted">-</span>
                            {% endif %}
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                {% if exchange.status == 'pending' %}
                                <button class="btn btn-success" onclick="updateExchangeStatus({{ exchange.id }}, 'completed')">
                                    <i class="bi bi-check"></i> 完成
                                </button>
                                <button class="btn btn-danger" onclick="updateExchangeStatus({{ exchange.id }}, 'cancelled')">
                                    <i class="bi bi-x"></i> 取消
                                </button>
                                {% else %}
                                <span class="text-muted">已处理</span>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="bi bi-clock-history text-muted display-4"></i>
                            <p class="text-muted mt-2">暂无兑换记录</p>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function updateExchangeStatus(exchangeId, status) {
    const statusText = {
        'completed': '完成',
        'cancelled': '取消'
    };
    
    if (confirm(`确定要将此兑换标记为"${statusText[status]}"吗？`)) {
        const formData = new FormData();
        formData.append('status', status);
        
        fetch(`/dashboard/reward-exchanges/${exchangeId}/update-status/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert(`兑换状态已更新为"${statusText[status]}"`, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('网络错误，请重试', 'error');
        });
    }
}

function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.querySelector('main').insertBefore(alertDiv, document.querySelector('main').firstChild);
    
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}
</script>
{% endblock %}